/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// 等待设备就绪
document.addEventListener('deviceready', function() {
    console.log('设备就绪，IP查询功能可用');
}, false);

// 表单提交处理
document.getElementById('ip-form').addEventListener('submit', function(e) {
    e.preventDefault();
    queryIP();
});

// 查询IP地址
function queryIP() {
    const submitBtn = document.getElementById('submit-btn');
    const loading = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');
    const resultContainer = document.getElementById('result-container');
    
    // 获取表单数据
    const formData = {
        token: document.getElementById('token').value.trim(),
        ip: document.getElementById('ip').value.trim()
    };
    
    // 验证token
    if (!formData.token) {
        showError('请输入API Token');
        return;
    }
    
    // 验证IP格式（如果输入了IP）
    if (formData.ip && !isValidIP(formData.ip)) {
        showError('IP地址格式不正确，请输入有效的IPv4或IPv6地址');
        return;
    }
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitBtn.textContent = '查询中...';
    loading.classList.add('show');
    errorMessage.classList.remove('show');
    resultContainer.classList.remove('show');
    
    // 构建请求参数
    const params = new URLSearchParams();
    params.append('token', formData.token);
    if (formData.ip) {
        params.append('ip', formData.ip);
    }
    
    // 发送POST请求
    fetch('https://v3.alapi.cn/api/ip', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params.toString()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络请求失败: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('API响应:', data);
        
        if (data.success && data.code === 200) {
            displayIPInfo(data.data);
        } else {
            showError(data.message || '查询失败，请检查参数');
        }
    })
    .catch(error => {
        console.error('请求错误:', error);
        showError('请求失败: ' + error.message + '。请检查网络连接或API Token是否正确');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.textContent = '查询';
        loading.classList.remove('show');
    });
}

// 验证IP地址格式
function isValidIP(ip) {
    // IPv4格式验证
    const ipv4Regex = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    // IPv6格式验证（简化版）
    const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$/;
    
    return ipv4Regex.test(ip) || ipv6Regex.test(ip);
}

// 显示错误信息
function showError(message) {
    const errorMessage = document.getElementById('error-message');
    errorMessage.textContent = message;
    errorMessage.classList.add('show');
}

// 显示IP信息
function displayIPInfo(data) {
    const resultContainer = document.getElementById('result-container');
    const ipInfo = document.getElementById('ip-info');
    
    let html = '';
    
    // IP基本信息
    html += '<div class="info-section">';
    html += '<div class="info-section-title">IP地址信息</div>';
    html += '<div class="info-grid">';
    html += `<div class="info-item"><div class="info-label">IP地址</div><div class="info-value">${data.ip || '未知'}</div></div>`;
    html += `<div class="info-item"><div class="info-label">IP范围</div><div class="info-value">${data.beginip || '未知'} - ${data.endip || '未知'}</div></div>`;
    html += `<div class="info-item"><div class="info-label">ISP运营商</div><div class="info-value">${data.isp || '未知'}</div></div>`;
    html += `<div class="info-item"><div class="info-label">城市编码</div><div class="info-value">${data.adcode || '未知'}</div></div>`;
    html += '</div>';
    html += '</div>';
    
    // 地理位置信息
    html += '<div class="info-section">';
    html += '<div class="info-section-title">地理位置</div>';
    html += '<div class="info-grid">';
    html += `<div class="info-item"><div class="info-label">大洲</div><div class="info-value">${data.continent || '未知'}</div></div>`;
    html += `<div class="info-item"><div class="info-label">国家</div><div class="info-value">${data.country || '未知'} ${data.country_en ? '(' + data.country_en + ')' : ''}</div></div>`;
    html += `<div class="info-item"><div class="info-label">国家代码</div><div class="info-value">${data.country_cc || '未知'}</div></div>`;
    html += `<div class="info-item"><div class="info-label">省份</div><div class="info-value">${data.province || '未知'}</div></div>`;
    html += `<div class="info-item"><div class="info-label">城市</div><div class="info-value">${data.city || '未知'}</div></div>`;
    html += `<div class="info-item"><div class="info-label">区县</div><div class="info-value">${data.district || '未知'}</div></div>`;
    html += `<div class="info-item"><div class="info-label">详细地址</div><div class="info-value">${data.pos || '未知'}</div></div>`;
    html += '</div>';
    html += '</div>';
    
    // 坐标信息
    if (data.lng && data.lat) {
        html += '<div class="info-section">';
        html += '<div class="info-section-title">坐标信息</div>';
        html += '<div class="info-grid">';
        html += `<div class="info-item"><div class="info-label">经度</div><div class="info-value">${data.lng}</div></div>`;
        html += `<div class="info-item"><div class="info-label">纬度</div><div class="info-value">${data.lat}</div></div>`;
        html += '</div>';
        html += `<a href="https://www.openstreetmap.org/?mlat=${data.lat}&mlon=${data.lng}&zoom=15" target="_blank" class="map-link">在地图上查看</a>`;
        html += '</div>';
    }
    
    ipInfo.innerHTML = html;
    
    // 显示结果容器
    resultContainer.classList.add('show');
    
    // 滚动到结果区域
    resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 尝试从本地存储加载token
    const savedToken = localStorage.getItem('ip_api_token');
    if (savedToken) {
        document.getElementById('token').value = savedToken;
    }
    
    // 保存token到本地存储
    document.getElementById('token').addEventListener('blur', function() {
        const token = this.value.trim();
        if (token) {
            localStorage.setItem('ip_api_token', token);
        }
    });
    
    console.log('IP查询页面加载完成');
});

